import StorageUtil from './BDStorageUtils'

const devBaseURL = 'http://localhost:8080';
const proBaseURL = 'http://localhost:8080';




export const BASE_URL = process.env.NODE_ENV === 'development' ? devBaseURL: proBaseURL;
export const TIMEOUT = 5000;
export const USER_STORAGE = 'user_storage'
export const USER_DOI = "doi"
export const PRIVATE_KEY = "key"
export const TOKEN = "token"


function ParsedUrl(url) {
  const parser = document.createElement("a");
  parser.href = url;

  // IE 8 and 9 dont load the attributes "protocol" and "host" in case the source URL
  // is just a pathname, that is, "/example" and not "http://domain.com/example".
  parser.href = parser.href;

  // IE 7 and 6 wont load "protocol" and "host" even with the above workaround,
  // so we take the protocol/host from window.location and place them manually
  if (parser.host === "") {
    const newProtocolAndHost = window.location.protocol + "//" + window.location.host;
    if (url.charAt(1) === "/") {
      parser.href = newProtocolAndHost + url;
    } else {
      // the regex gets everything up to the last "/"
      // /path/takesEverythingUpToAndIncludingTheLastForwardSlash/thisIsIgnored
      // "/" is inserted before because IE takes it of from pathname
      const currentFolder = ("/" + parser.pathname).match(/.*\//)[0];
      parser.href = newProtocolAndHost + currentFolder + url;
    }
  }
  const result = {}
  // copies all the properties to this object
  const properties = ['host', 'hostname', 'hash', 'href', 'port', 'protocol', 'search'];
  let i = 0, n = properties.length;
  for (; i < n; i++) {
    result[properties[i]] = parser[properties[i]];
  }
  // pathname is special because IE takes the "/" of the starting of pathname
  result.pathname = (parser.pathname.charAt(0) !== "/" ? "/" : "") + parser.pathname;
  return result
}

function proxy(url, options){

  const networkCard = StorageUtil.getNetworkCard()
  const urlInfo = ParsedUrl(url)
  console.log(urlInfo)
  console.log("pathname: " + urlInfo.pathname)
  console.log(networkCard)
  console.log(options)

  let newUrl = urlInfo.href;
  if(urlInfo.pathname.startsWith('/doa/reg')){
    if(networkCard?.reg){
      newUrl = urlInfo.href.replace(urlInfo.host, networkCard?.reg)
    }
  }else if(urlInfo.pathname.startsWith('/doa/irs/')){
    if(networkCard?.irs){
      newUrl = urlInfo.href.replace(urlInfo.host, networkCard?.irs)
    }
  }else if(urlInfo.pathname.startsWith('/doa/user/')){

    console.log("=====common user login===")
    if(networkCard?.irs){
      newUrl = urlInfo.href.replace(urlInfo.host, networkCard?.irs)
    }

    if(urlInfo.pathname.startsWith('/doa/user/login')){
      if(options?.data?.doi?.endsWith('dou.ADMIN')){
        console.log("=====irs admin login===")
        if(networkCard?.grs){
          newUrl = urlInfo.href.replace(urlInfo.host, networkCard?.grs)
        }
      }
    }else if(urlInfo.pathname.startsWith('/doa/user/currentUser')){
      if(options?.params?.doi?.endsWith('dou.ADMIN')){
        console.log("=====irs admin info===")
        if(networkCard?.grs){
          newUrl = urlInfo.href.replace(urlInfo.host, networkCard?.grs)
        }
      }
    }
  }else if(urlInfo.pathname.startsWith('/api/grs/')){
    if(networkCard?.grs){
      newUrl = urlInfo.href.replace(urlInfo.host, networkCard?.grs)
    }
  }else if(urlInfo.pathname.startsWith('/doa/repo/')){
    if(networkCard?.repo){
      newUrl = urlInfo.href.replace(urlInfo.host, networkCard?.repo)
    }
  }

  console.log("redirect url: \n" + newUrl)

  return newUrl
}


export const requestInterceptor = (url, options) => {

  const user = StorageUtil.getUsers()
  const token = user?.token
  const doi = user?.doi
  console.log(url)
  //标准做法是加在Authorization上，现在我们通过accessToken和doi两个字段传递相关信息
  const authHeader = doi != null ? {Authorization : 'Bearer ' + token, accessToken : token, doi : doi} : {}

  let newUrl = proxy(url, options)

  return {
    url : `${newUrl}`,
    options:{...options, interceptors:true, headers:authHeader}
  }
}

//请求响应的拦截器，打印出reponse
export const responseInterceptor = async (response) => {
  const res = await response.clone().json()
  console.log(res)
  return {...res}
}

